package com.ow.framework.controller.servlet;



import java.io.File;
import java.net.MalformedURLException;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.ibatis.io.Resources;
import org.apache.log4j.Logger;

import com.ow.framework.common.Constant;
import com.ow.framework.data.handler.CollectionInit;
import com.ow.framework.data.handler.config.PermissionConfig;
import com.ow.framework.data.handler.config.SqlSessionConfig;
import com.ow.framework.exception.DetailException;

   
public class InitServlet extends HttpServlet
{
	static Logger log = Logger.getLogger(Constant.FRAMEWORK);
	private static final long serialVersionUID = 2994828437175265025L;
	private CollectionInit collectionInit;

	public void init(ServletConfig param) throws ServletException
	{
		try
		{
            String configFile = "config" + File.separator + "framework.properties";
    		Properties props = Resources.getResourceAsProperties(configFile);
    		String dsname = props.getProperty("framework.datasource.name") == null ? "" : props.getProperty("framework.datasource.name").trim();
    		String delSqlid = props.getProperty("framework.permission.delete") == null ? "" : props.getProperty("framework.permission.delete").trim();
    		String insertSqlid = props.getProperty("framework.permission.insert") == null ? "" : props.getProperty("framework.permission.insert").trim();
    		String pmsStartCode = props.getProperty("framework.permission.start.code") == null ? "" : props.getProperty("framework.permission.start.code").trim();
    		String isInitPerm =  props.getProperty("framework.isInitPerm") == null ? "" : props.getProperty("framework.isInitPerm").trim();
    		Constant.PERMISSION_START_CODE = pmsStartCode;
			String filePath = param.getServletContext().getRealPath("/");
			if(filePath == null){
				try {
					filePath = param.getServletContext().getResource("/").toString();
				} catch (MalformedURLException e) {
					e.printStackTrace();
				}
			}
			String relPath = filePath + "WEB-INF" + File.separator + "config" + File.separator;
			String filePermission = relPath+"module";
			String fileIbtatisConfig = "com" 
				+ File.separator + "ow" 
				+ File.separator + "framework" 
				+ File.separator + "data" 
				+ File.separator + "dao"	
				+ File.separator + "xml"					
				+ File.separator + "ibatis.config.xml";
			collectionInit = new CollectionInit();
			collectionInit.addInit(new SqlSessionConfig(fileIbtatisConfig));
			if("true".equals(isInitPerm)){
				collectionInit.addInit(new PermissionConfig(filePermission,dsname,delSqlid,insertSqlid));
			}
			collectionInit.doInit();
		}
		catch (Exception e)
		{
			String debug = DetailException.expDetail(e, InitServlet.class);
			log.debug(debug);
			/**异常退出系统*/
			System.exit(0);
		}
	}
    
    
	public void destroy()
	{
		
	}
}

